package main

import (
	"bytes"
	"context"
	"syscall"

	"github.com/hanwen/go-fuse/v2/fs"
	"k8s.io/client-go/tools/remotecommand"
)

type File struct {
	fs   *KubernetesFS
	name string
	fs.Inode
}

func (f *File) Open(ctx context.Context, flags uint32) syscall.Errno {
	return 0 // 无需特殊处理
}

func (f *File) Read(ctx context.Context, dest []byte, offset int64) (uint32, syscall.Errno) {
	// 执行 cat 命令以读取文件内容
	execRequest := f.fs.clientset.CoreV1().RESTClient().Post().
		Resource("pods").
		Name(f.fs.podName).
		Namespace(f.fs.namespace).
		SubResource("exec").
		Param("container", f.fs.container).
		Param("command", "cat").
		Param("command", f.name).
		Param("stdin", "false").
		Param("stdout", "true").
		Param("stderr", "true").
		Param("tty", "false")

	exec, err := remotecommand.NewSPDYExecutor(f.fs.config, "POST", execRequest.URL())
	if err != nil {
		return 0, syscall.EIO
	}

	var stdout bytes.Buffer
	err = exec.Stream(remotecommand.StreamOptions{
		Stdout: &stdout,
		Tty:    false,
	})
	if err != nil {
		return 0, syscall.EIO
	}

	// 将输出复制到目标缓冲区
	n := copy(dest, stdout.Bytes())
	return uint32(n), 0
}
